import React, {useEffect, useMemo, useState} from "react";
import {createEditor, Descendant, Editor, Transforms,} from 'slate'
import {Editable, Slate, withReact} from "slate-react";
import "./index.css"
import {withCursors, withYjs} from "@slate-yjs/core";

interface SlateEditorProps {
    initialValue: Descendant[],
    onChange: (value: Descendant[]) => void;
}

const SlateEditor: React.FC<SlateEditorProps> = ({initialValue, onChange}) => {
    const handleChange=(value:Descendant[])=>{
        const isAstChange = editor.operations.some(
            op => 'set_selection' !== op.type
        )
        if (isAstChange) {
            // Save the value to Local Storage.
            onChange(value)
        }
    }

    const editor = useMemo(()=> {
        const editor = createEditor();
        const e = withReact(editor);
        const {normalizeNode} = e;
        // shareType.insert(0, "my link", { a: { href: 'https://..' } })

        e.normalizeNode = entry => {
            const [node] = entry;
            if (!Editor.isEditor(node) || node.children.length > 0) {
                return normalizeNode(entry);
            }
            Transforms.insertNodes(editor, initialValue, {at: [0]});
        }
        return e;
    },[]);
        return (
            <Slate editor={editor} initialValue={initialValue} onChange={onChange}>
                <Editable style={{
                    width: "100%",
                    height: "100%"
                }}/>
            </Slate>
        );
    }
    export default SlateEditor;
